package org.linkminder.servlet;

import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;

import org.linkminder.LinkMinder;
import org.linkminder.LinkMinderException;

import com.google.wave.api.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletContext;

/**
 * 
 * @author jackpark
 * @author mark.carranza
 *
 */


@SuppressWarnings("serial")
public class LinkMinderServlet extends AbstractRobotServlet {
	
	 /**
	   * The key of a wave id.
	   */
	  private static final String WAVE_ID = "waveID";
	  
	  /**
	   * The key of a wavelet id.
	   */
	  private static final String WAVELET_ID = "waveletID";
	  
	  /**
	   * The key of a blip id.
	   */
	  private static final String BLIP_ID = "blipID";
	  
	private static final Logger log =
	      Logger.getLogger(LinkMinderServlet.class.getName());
	private LinkMinder brains;
	
	public void init()
    	throws ServletException {
		super.init();
		log.info("LinkMinderServlet.init- ");
		try {
			ServletConfig config = super.getServletConfig();
			ServletContext m_context = config.getServletContext();
	        File  	m_homeDir = new File(m_context.getRealPath("/")); 
	        File webInfDir = new File(m_homeDir, "WEB-INF");
	        //path for RDBMS database
	        File data = new File(webInfDir, "data");
			brains = new LinkMinder(data.getAbsolutePath());
		} catch (Exception e) {
			log.info("LinkMinderServlet.init error "+e.getMessage());
			throw new ServletException(e);
		}
	
	}
    public void destroy() {
     	brains.shutDown();
    }

	/* (non-Javadoc)
	 * @see com.google.wave.api.AbstractRobotServlet#processEvents(com.google.wave.api.RobotMessageBundle)
	 */
	@Override
	public void processEvents(RobotMessageBundle bundle) {
	    Wavelet wavelet = bundle.getWavelet();
	    
	    // start to gather ids for new wavelet (not finished)	    
	    String waveID = wavelet.getDataDocument(WAVE_ID);
	    
	    Blip rootBlip = wavelet.getRootBlip();
	    FormElement inputText = 
    		new FormElement(ElementType.INPUT, "entry");
		log.info("LinkMinderServlet.processEvents- ");

		// more than one wavelet in a wave
	    if (bundle.wasSelfAdded()) {
			log.info("LinkMinderServlet.processEvents- wasSelfAdded");
	        TextView textView = rootBlip.getDocument();
	        textView.append("What are you thinking?");
	        FormView formView = textView.getFormView();	    	
	    	formView.append(inputText);
	    	FormElement rootSubmitButton = 
	    		new FormElement(ElementType.BUTTON, "title", "enter");
	    	// this was NOT visible when appended to formView
	    	textView.appendElement(rootSubmitButton);
	    	// "done" the rootBlip
       }
	    
	    Blip eventBlip = null;
	    Blip childBlip = null;
	    TextView textView = null;
	    FormView formView = null;
	    FormElement inputElement = null;
	    String entry = "";
	    String buttonClicked = "";
	   // Handle various events.
	    for (Event e : bundle.getEvents()) {
	      switch (e.getType()) {
	        case FORM_BUTTON_CLICKED:

	    		log.info("LinkMinderServlet.processEvents formButtonClicked: " + e.getButtonName());
	    		
	    		entry = getBlipEntry(e.getBlip());
	    		
	    		log.info("LinkMinderServlet.processEvents formButtonClicked inputElement: " + entry);
	    		// todo: test text not empty or duplicate
	    			    		
	    		if (e.getButtonName().equals("title")) {
	    			// create a child wavelet under root blip
	    			log.info("LinkMinderServlet.processEvents formButtonClicked: createChild wavelet of root blip");
	    			
	    			String annotationWriteBack = String.valueOf(Math.random());
	    			Wavelet listWavelet = 
	    				wavelet.createWavelet(wavelet.getParticipants(), annotationWriteBack);
	    			
	    			childBlip = listWavelet.appendBlip();
	    	        textView = childBlip.getDocument();
	    	        formView = textView.getFormView();	    	
	    	    	FormElement submitButton = 
	    	    		new FormElement(ElementType.BUTTON, "entry", "enter");
	    	    	formView.append(inputText);
	    	    	formView.append(submitButton);
	    		}	    		
	          // theoretically speaking, this could be a button to "clear the screen" in the root blip
	          //TODO generalize this to New Question, New Answer, New Pro, New Con
	         // newPost(bundle, wavelet);
	          break;
	        case BLIP_SUBMITTED:
	    		log.info("LinkMinderServlet.processEvents blipSubmitted ");
	          // this is where we will handle a new idea using LinkMinder
	     //     if ("false".equals(wavelet.getDataDocument(TOC_FLAG))) {
	     //       if (!wavelet.getDataDocument(TITLE).equals(wavelet.getTitle())) {
	     //         updateTableOfContents(bundle, wavelet);
	     //       }
	     //     }
	          break;
	        case DOCUMENT_CHANGED:
	    		log.info("LinkMinderServlet.processEvents documentChanged ");
	          // probably don't need this one
	      //    String newIds = wavelet.getDataDocument("_new_ids_");
	      //    if (newIds != null && !newIds.isEmpty()) {
	      //      for (String line : newIds.split(LINE_SEP_REGEX)) {
	      //        if (line.startsWith("<p>" + wavelet.getDataDocument(BLIP_ID))) {
	      //          String[] pollBlip = line.split(FIELD_SEP_REGEX);
	       //         String participantPollBlipId = pollBlip[1];
	       //         pollBlip = participantPollBlipId.split(" ");
	       //         participantPollBlipId = pollBlip[2];
	       //         wavelet.setDataDocument(BLIP_ID, participantPollBlipId);
	       //       }
	      //      }
	       //     wavelet.setDataDocument("_new_ids_", "");
	       //   }
	          break;
	      }
	    }
	}
	
	private String getBlipEntry(Blip blip) {
		// get text in "entry" field		
		return blip.getDocument().getFormView().getFormElement("entry").getValue();
	}
}
